/*
 * @lc app=leetcode.cn id=331 lang=cpp
 *
 * [331] 验证二叉树的前序序列化
 */

// @lc code=start
class Solution {
public:
    bool isValidSerialization(string preorder) {
        stack<char> stk;
        int size =  preorder.size();
        int num = 0;
        for(int i = size - 1;i >= 0; i--)
        {
            if(preorder[i] == ',')
            {
                continue;
            }

            if(preorder[i] == '#')
            {
                num++;
            }
            else
            {
                while(i > 0 && preorder[i] != ',')
                {
                    i--;
                }
                if(num >= 2)
                {
                    num--;
                }
                else 
                    return false;
            }

        }
        if(num!=1)
        {
            return false;
        }
        return true;
    }
};
// @lc code=end

